package org.practice.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.practice.dao.LogInfoDao;
import org.practice.dao.UserDao;
import org.practice.model.LogInfo;
import org.practice.model.User;
import org.practice.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component(value="userService")
public class UserServiceImpl implements UserService{
	private UserDao userDao;
	private LogInfoDao logInfoDao;
	
	@Resource(name="userDao")
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	@Resource(name="logDao")
	public void setLogInfoDao(LogInfoDao logInfoDao) {
		this.logInfoDao = logInfoDao;
	}
	
	
	/**
	 * 事务传播性：默认REQUIRED
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void addUser(User user){
		LogInfo logInfo=new LogInfo();
		logInfo.setOperTime(new Date());
		logInfo.setMsg("新增一条用户记录！");
		logInfoDao.addLogInfo(logInfo);
		userDao.addUser(user);
		/*抛出一个运行时异常，让事务回滚
		 * sessionFactory.openSession()得到的session无事务，即使程序抛异常也会将脏数据插入数据库
		 * sessionFactory.getCurrentSession();保证获得开启事务的session，程序抛异常数据不会进库
		 */
		throw new HibernateException("运行时异常！");
	}

	public User validateUser(String email, String password) {
		return userDao.validateUser(email, password);
	}


	public User verifyUser(Integer id, String code) {
		return userDao.verifyUser(id, code);
	}

	public User findUserById(Integer id) {
		return userDao.findUserById(id);
	}
	public void updateUser(User user){
		userDao.updateUser(user);
	}

	public boolean checkEmail(String email) {
		return userDao.checkEmail(email);
	}
	
	
}
